#!/usr/bin/env python
# -*- coding: utf-8 -*-

#     Copyright 2008 OtÃ¡vio Pontes <otaviobp@gmail.com>
#
#     This file is part of amarokfs-fuse.
#
#     amarokfs-fuse is free software: you can redistribute it and/or 
# 	modify it under the terms of the GNU General Public License as published by
#     the Free Software Foundation, either version 3 of the License, or
#     (at your option) any later version.
#
#     amarokfs-fuse is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#
#     You should have received a copy of the GNU General Public License
#     along with amarokfs-fuse.  If not, see 
# 	<http://www.gnu.org/licenses/>.

import os
from pysqlite2 import dbapi2 as sqlite
from logging import warning as log

class Music(dict):
    """class to store information about a song"""
    def __init__ (self):
        self["__filetype"] = "symlink"

class AmarokDB:
    """Class to get information from the amarok dabase file(collection.db), 
    using sqlite"""
    
    def __init__(self, dbPath):
        """
        Create a new AmarokDB connection
        dbPath - Path to database file (collection.db)
        """
        self.__dbPath=dbPath
        self.__connection = sqlite.connect(self.__dbPath)
        self.__cursor = self.__connection.cursor()

    def getValues (self, field, table, filter = ""):
        """
        Get the field from the table with a select statement.
        """
        query = 'select %s from %s' % (field,  table)
        if filter != "":
            query += " where " + filter
        self.__cursor.execute(query)
        
        data=self.__cursor.fetchone()
        while data != None:
            yield data[0].encode("utf-8")
            data=self.__cursor.fetchone()

    def getArtistNames (self):
        return self.getValues("Name", "artist")

    def getAlbumNames (self):
        return self.getValues("Name", "album")

    def getGenreNames (self):
        return self.getValues("Name", "genre")
    
    def getMusicTitlesMp3 (self, field="", value=""):
        """
        field_value: Tuple with 2 elements, the field/table name and the value desired.     
        Return an generator with na music tiles, filtered by the info in field_value.
        ex: if field_value=('artist','beatles'), retuns all the beatles' songs.
        It appends the the mp3 extension. 
        """
        if field == "" or value == "":
            query = 'select title from tags'
        else:
            query = 'select title from tags t, %s t2 where t.%s = t2.id and t2.name="%s"' % (field, field, value)
        self.__cursor.execute(query)
    
        data=self.__cursor.fetchone()
        while data != None:
            yield data[0].encode("utf-8") + ".mp3"
            data=self.__cursor.fetchone()

    def getMusicTitlesAndUrl (self, field, value):
        """Get a dictionary with instances of Music, containing information about the songs"""
        if field == "" or value == "":
            query = 'select title,url from tags'
        else:
            query = 'select t.title,d.lastmountpoint, t.url from tags t, %s t2, devices d where t.deviceid = d.id and t.%s = t2.id and t2.name="%s"' % (field, field, value)
        self.__cursor.execute(query)
    
        data=self.__cursor.fetchone()
        d={}
        while data != None: 
            title=data[0].encode("utf-8") + ".mp3" 
            d[title] = Music()
            d[title]['__url'] = data[1] + os.sep + data[2]
            data=self.__cursor.fetchone()
        return d

    def getAll(self):
        return self.getMusicTitlesMp3(())


if __name__ == "__main__":   
    a = AmarokDB("collection.db")
    print unicode(a.getArtistNames()[1][0]).encode('iso-8859-1');
